<template>
  <div class="position-manage">
    <!-- 筛选栏：状态筛选 + 发布按钮 -->
    <div class="filter-bar">
      <el-select
        v-model="statusFilter"
        placeholder="选择状态"
        @change="handleStatusChange"
        clearable
        style="width: 180px"
      >
        <el-option label="全部" value=""></el-option>
        <el-option label="审核中" value="pending"></el-option>
        <el-option label="已发布" value="published"></el-option>
        <el-option label="审核失败" value="failed"></el-option>
      </el-select>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="filteredTableData"
      border
      stripe
      :loading="loading"
      row-key="id"
      style="margin-top: 15px; width: 100%"
    >
      <!-- 序号列 -->
      <el-table-column
        type="index"
        label="序号"
        width="50"
        align="center"
      ></el-table-column>

      <!-- 职位名称 -->
      <el-table-column
        prop="current.positionName"
        label="职位名称"
        width="160"
        align="center"
        show-overflow-tooltip
      ></el-table-column>

      <!-- 职位类型 -->
      <el-table-column
        prop="current.positionType"
        label="职位类型"
        width="80"
        align="center"
      ></el-table-column>

      <!-- 学历要求 -->
      <el-table-column
        prop="current.education"
        label="学历要求"
        align="center"
        :formatter="formatEducation"
      ></el-table-column>

      <!-- 薪资范围 -->
      <el-table-column label="薪资范围" width="150" align="center">
        <template #default="scope">
          {{ scope.row.current.lowestSalaryMonth }} -
          {{ scope.row.current.highestSalaryMonth }} 元/月
        </template>
      </el-table-column>

      <!-- 发布时间 -->
      <el-table-column
        prop="current.startAt"
        label="发布时间"
        width="100"
        align="center"
        :formatter="formatDate"
      ></el-table-column>

      <!-- 截止日期 -->
      <el-table-column
        prop="current.endAt"
        label="截止日期"
        width="100"
        align="center"
        :formatter="formatDate"
      ></el-table-column>

      <!-- 审核状态 -->
      <el-table-column label="审核状态" width="200" align="center">
        <template #default="scope">
          <PositionStatusTag
            :status="scope.row.status"
            :scene="scope.row.scene"
            :failed-message="scope.row.failedMessage"
          />
        </template>
      </el-table-column>

      <el-table-column
        prop="userInfo.name"
        label="发布人"
        width="100"
        align="center"
        v-if="isAdmin"
      ></el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="240" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row.id)"
            >查看</el-button
          >
          <template v-if="scope.row.status === 'VERIFY_COMPANY_REVIEW'">
            <el-button
              type="success"
              size="small"
              @click="handleApprove(scope.row.id)"
              >通过</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleReject(scope.row.id)"
              >不通过</el-button
            >
          </template>
          <!-- 管理员审核状态下显示提示 -->
          <span
            v-else-if="scope.row.status === 'VERIFY_MANAGER_REVIEW'"
            class="status-tip"
          >
            等待管理员审核中
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next"
        :disabled="total === 0"
        style="margin-top: 15px"
      />
    </div>
  </div>
</template>

<script>
import PositionStatusTag from "@/views/CompanyViews/company-position/component/PositionStatusTag.vue";
import {
  getUserPublishPositions,
  getUserPositions,
  getCompanyPublishPositions,
  getCompanyPositions,
  companyVerifyPublishPosition,
  companyVerifyPublishPositionFailed,
  companyVerifyChangePosition,
  companyVerifyChangePositionFailed,
} from "@/api/recuriter/position";

export default {
  components: {
    PositionStatusTag,
  },
  data() {
    return {
      statusFilter: "",
      allTableData: [],
      currentPage: 1,
      pageSize: 5,
      loading: false,
    };
  },
  computed: {
    userType() {
      return this.$store.state.recruiter.userInfo?.type || "";
    },
    isAdmin() {
      return ["BOSS", "MANAGEMENT"].includes(this.userType);
    },
    userId() {
      return this.$store.state.recruiter.userInfo?.userId || "";
    },
    filteredTableData() {
      let filtered = [...this.allTableData];
      if (this.statusFilter === "pending") {
        filtered = filtered.filter((item) =>
          ["VERIFY_COMPANY_REVIEW", "VERIFY_MANAGER_REVIEW"].includes(
            item.status
          )
        );
      } else if (this.statusFilter === "published") {
        filtered = filtered.filter((item) => item.status === "NORMAL");
      } else if (this.statusFilter === "failed") {
        filtered = filtered.filter((item) =>
          ["VERIFY_COMPANY_FAILED", "VERIFY_MANAGER_FAILED"].includes(
            item.status
          )
        );
      }

      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return filtered.slice(startIndex, endIndex);
    },
    total() {
      if (this.statusFilter === "pending") {
        return this.allTableData.filter((item) =>
          ["VERIFY_COMPANY_REVIEW", "VERIFY_MANAGER_REVIEW"].includes(
            item.status
          )
        ).length;
      } else if (this.statusFilter === "published") {
        return this.allTableData.filter((item) => item.status === "NORMAL")
          .length;
      } else if (this.statusFilter === "failed") {
        return this.allTableData.filter((item) =>
          ["VERIFY_COMPANY_FAILED", "VERIFY_MANAGER_FAILED"].includes(
            item.status
          )
        ).length;
      }
      return this.allTableData.length;
    },
  },
  created() {
    this.loadTableData();
  },
  methods: {
    async loadTableData() {
      this.loading = true;
      try {
        let rawData = [];
        const [
          companySuccessRes,
          personSuccessRes,
          personPendingRes,
          companyPendingRes,
        ] = await Promise.all([
          getCompanyPositions(),
          getUserPositions(),
          getUserPublishPositions(),
          getCompanyPublishPositions(),
        ]);

        rawData = [
          ...companySuccessRes.data,
          ...personSuccessRes.data,
          ...personPendingRes.data,
          ...companyPendingRes.data,
        ];

        const validData = rawData.filter((item) => {
          return item.current && typeof item.current === "object";
        });

        const map = new Map();
        for (const item of validData) {
          const { id, source } = item;
          if (!map.has(id)) {
            map.set(id, item);
          } else {
            const existingItem = map.get(id);
            if (existingItem.source === "personal" && source === "company") {
              map.set(id, item);
            }
          }
        }
        const uniqueValidData = [...map.values()];

        const filteredData = uniqueValidData.filter((item) => {
          if (
            ["VERIFY_COMPANY_REVIEW", "VERIFY_MANAGER_REVIEW"].includes(
              item.status
            ) &&
            item.userInfo.userId === this.userId
          ) {
            return false;
          }
          return true;
        });
        this.allTableData = filteredData;
        console.log(this.allTableData);
        this.currentPage = 1;
      } catch (error) {
        console.error("加载岗位数据失败：", error);
        this.$message.error("加载岗位数据失败，请重试");
      } finally {
        this.loading = false;
      }
    },

    // 格式化日期
    formatDate(row, column, cellValue) {
      if (!cellValue) return "-";
      const date = new Date(cellValue);
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    },

    // 格式化学历
    formatEducation(row, column, cellValue) {
      const eduMap = {
        COLLEGE: "大专",
        UNDERGRADUATE: "本科",
        MASTER: "硕士",
        DOCTOR: "博士",
        OTHER: "其他",
      };
      return eduMap[cellValue] || cellValue;
    },

    // 状态筛选变化
    handleStatusChange() {
      this.currentPage = 1; // 重置页码
    },

    // 分页页码变化
    handleCurrentChange(page) {
      this.currentPage = page;
      document.querySelector(".el-table").scrollTop = 0;
    },

    handleView(id) {
      const targetItem = this.allTableData.find((item) => item.id === id);
      this.$router.push({
        name: "position-detail",
        params: { id, status: targetItem.status, scene: targetItem.scene },
        query: { from: "admin-position-list" },
      });
    },

    // 公司审核通过
    async handleApprove(id) {
      const targetItem = this.allTableData.find((item) => item.id === id);

      try {
        if (targetItem.scene === "positionId") {
          const updateres = await companyVerifyChangePosition(id);
          this.$store.commit("recruiter/SET_TOKEN", updateres.data.data);
        } else {
          const initialres = await companyVerifyPublishPosition(id);
          this.$store.commit("recruiter/SET_TOKEN", initialres.data.data);
        }

        this.$message.success("审核已通过");
        this.loadTableData();
      } catch (error) {
        this.$message.error("审核失败，请重试");
      }
    },

    // 公司审核不通过
    async handleReject(id) {
      const targetItem = this.allTableData.find((item) => item.id === id);
      this.$prompt("请输入拒绝原因", "审核拒绝", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^.{1,100}$/,
        inputErrorMessage: "拒绝原因长度在1-100个字符之间",
      })
        .then(async ({ value }) => {
          try {
            if (targetItem.scene === "positionId") {
              const updateres = await companyVerifyChangePositionFailed(
                id,
                value
              );
              this.$store.commit("recruiter/SET_TOKEN", updateres.data.data);
            } else {
              const initialres = await companyVerifyPublishPositionFailed(
                id,
                value
              );
              this.$store.commit("recruiter/SET_TOKEN", initialres.data.data);
            }
            this.$message.success("已拒绝该职位");
            this.loadTableData();
          } catch (error) {
            this.$message.error("操作失败，请重试");
          }
        })
        .catch(() => {
          this.$message.info("已取消拒绝");
        });
    },
  },
};
</script>

<style scoped>
.position-manage {
  padding: 20px;
}
.filter-bar {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.pagination-container {
  text-align: right;
}

/* 表格样式优化 */
::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

::v-deep .el-table .el-tag {
  margin: 0;
}
.status-tip {
  display: inline-block;
  margin-left: 10px;
  color: #86909c;
  font-size: 12px;
}
</style>